package com.moonshineproject.commands
{
	import com.moonshineproject.GlobalEventDispatcher;
	import com.moonshineproject.IDEModel;
	import com.moonshineproject.events.CloseTabEvent;
	import com.moonshineproject.view.IContentWindow;
	
	import flash.desktop.NativeApplication;
	import flash.display.DisplayObject;
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;

	public class QuitCommand implements ICommand
	{

		public function execute(event:Event):void
		{
			var editors:ArrayCollection = IDEModel.getInstance().editors;
			var ged:GlobalEventDispatcher = GlobalEventDispatcher.getInstance();
			
			for each (var tab:IContentWindow in editors)
			{
				if (!tab.isChanged())
				{
					ged.dispatchEvent( new CloseTabEvent(tab as DisplayObject) );
				}
			}
			
			// One editor is auto-created when last is removed
			if (editors.length == 1 
				&& editors.getItemAt(0).isChanged() == false)
			{
				NativeApplication.nativeApplication.exit();
			}
			else
			{
				event.preventDefault();
				ged.dispatchEvent( new CloseTabEvent(editors.getItemAt(0) as DisplayObject) );
			}
		}
		
	}
}